// pages/prodution/prodution.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        primary: app.globalData.primary, // 主题色
        ossPath: app.globalData.ossPath,
        jiaji: false, // 加急
        productionId: '', // 产品编号
        productionBanner: [], // 轮播
        productionInfo: {}, // 产品信息
        offer: {}, // 报价  
        description: [], // 商品描述
        show: false, // 优惠信息
        printprice: {}, // 报价信息,
        doucumentNum: null, // 模板编号
        thumb: null, //缩略图
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        //设置主题色
        if (app.globalData.primary) {
            this.setData({ primary: app.globalData.primary })
            app.usePrimary(app.globalData.primary)
        }
        wx.setNavigationBarColor({
            frontColor: '#ffffff',
            backgroundColor: app.globalData.primary,
        })
        this.setData({
            productionId: options.id,
            doucumentNum: options.d,
            thumb:options.thumb
        })
        console.log(options)
        this.getProductionInfo(options.id);
    },
    toggleJiaJi: function() {
        this.setData({ jiaji: !this.data.jiaji })
        var obj = this.setPriceParams();
        this.getPrice(obj);
    },
    getProductionInfo: function(id) {
        wx.request({
            url: app.globalData.serverPath + '/ProductSheet?TypeID=' + id,
            success: ({
                data
            }) => {
                this.setData({
                    productionBanner: data[0].Albums || []
                })
                this.filterData(data[0])
            }
        })
    },
    filterData: function(data) { // 过滤
        data = this.setIsDefault(data, 0, 'Pages')
        data = this.setIsDefault(data, 0, 'Quantities')
        data = this.setIsDefault(data, 0, 'Attributes', false)
        data.ProductType.Price = parseFloat(data.ProductType.Price).toFixed(2);
        data.Coupons.reverse()
        data.Coupons.forEach(item => {
            var date = new Date(item.CreateTime)
            var end = item.EffectiveDays * 24 * 60 * 60 * 1000 + date.getTime();
            item.start = date.toLocaleDateString().replace(/\//g, '.');
            item.end = new Date(end).toLocaleDateString().replace(/\//g, '.');
            
        })
        this.setData({
            productionInfo: data
        })
        var obj = this.setPriceParams();
        this.getPrice(obj)
        var reg = /src=".*?"/ig;
        var arr = data.Description.match(reg);
        if (arr) {
            arr.forEach((item, i)=> {
                arr[i] = arr[i].replace(/(src=")|"/g, '')
                arr[i] = arr[i].replace(/http/g, 'https')
                console.log(arr[i],123)
            })
            this.setData({ description: arr })
        }
    },
    setIsDefault: function(data, index, type, single = true, i) { //设置默认值
        if (single) { // arr没有嵌套
            if (type == 'Crafts') {
                    data[type][index]['IsDefault'] = data[type][index]['IsDefault'] ? false : true
                // data[type].forEach((item, i) => {
                // })
            } else {
                data[type].forEach((item, i) => {
                    data[type][i]['IsDefault'] = false
                    if (i == index) {
                        data[type][i]['IsDefault'] = true
                    }
                })

            }
        } else {
            if (i != undefined) {
                console.log(data[type][i])
                data[type][i].Items.forEach((item, j) => {
                    item['IsDefault'] = false
                    if (j == index) {
                        item['IsDefault'] = true
                    }
                })
            } else {
                data[type].forEach((items, i) => {
                    items.Items.forEach((item, j) => {
                        item['IsDefault'] = false
                        if (j == index) {
                            item['IsDefault'] = true
                        }
                    })
    
                })
            }
            
            
        }
        return data;
    },
    changeDefault: function(e) { // 改变默认选中
        let index = e.currentTarget.dataset.index,
            type = e.currentTarget.dataset.type,
            i = e.currentTarget.dataset.i;
        if (type == 'Attributes') {
            this.data.productionInfo = this.setIsDefault(this.data.productionInfo, index, type, false, i );
        } else {
            this.data.productionInfo = this.setIsDefault(this.data.productionInfo, index, type);
        }
        this.setData({
            productionInfo: this.data.productionInfo
        })
        let obj = this.setPriceParams();
        this.getPrice(obj)

    },
    getIsDefault(arr) { // 获取默认参数id
        let id;
        if (arr.length == 0) id = ''
        for (var i = 0; i < arr.length; i++) {
            if (arr[i]['IsDefault']) {
                id = arr[i].ID   
                break 
            }
        }
        return id
    },
    setPriceParams: function () { // 设置报价参数
        var printprice = { // 获取价格的参数
            SheetId: this.data.productionInfo.ID,
            SizeId: this.getIsDefault(this.data.productionInfo.Sizes),
            PageId: this.getIsDefault(this.data.productionInfo.Pages),
            QuantityId: this.getIsDefault(this.data.productionInfo.Quantities),
            Attributes: '',
            Crafts: '',
            Urgent: this.data.jiaji,
            Count: 0,
            OrderType: this.data.doucumentNum ? 3 : 1,
            FileName: '',
            FilePath: '',
            DocumentNum: this.data.doucumentNum || '',
            Thumb: this.data.thumb || '',
            Selected: 1
        };
        this.data.productionInfo.Attributes.forEach((item, index) => {
            let type;
            item['Items'].forEach((tmp, i) => {
                if (tmp['IsDefault']) {
                    printprice.Attributes += tmp.ID + ','
                    type = tmp['IsDefault']
                }
            })
            if (!type) {
                this.data.productionInfo.Attributes[index]['Items'][0]['IsDefault'] = true
                printprice.Attributes += this.data.productionInfo.Attributes[index]['Items'][0].ID + ','
            }
        })

        this.data.productionInfo.Crafts.forEach((item, index) => {
            let type;
            if (item['IsDefault']) {
                printprice.Crafts += item.ID + ','
                type = item['IsDefault']
            }
        })

        if (printprice.Attributes.lastIndexOf(',') == printprice.Attributes.length - 1) {
            printprice.Attributes = printprice.Attributes.slice(0, -1)
        }
        if (printprice.Crafts.lastIndexOf(',') == printprice.Crafts.length - 1) {
            printprice.Crafts = printprice.Crafts.slice(0, -1)
        }
        this.setData({ printprice: printprice})
        return printprice
    },
    filterPrice: function(data) { // 过滤报价结果
        data.TotalPrice = parseFloat(data.TotalPrice).toFixed(2);
        let date = new Date();
        let time = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 16);
        if (date.getTime() > time.getTime()) {
            data.TotalProductionTime += 1
        }
        return data
    },
    // 获取报价结果
    getPrice: function (obj) {
        let params = '';
        for (let item in obj) {
            params += item + '=' + obj[item] + '&'
        }
        wx.request({
            url: app.globalData.serverPath + '/printprice',
            method: "POST",
            header: app.globalData.header,
            data: params,
            success: ({
                data
            }) => {

                this.data.offer = this.filterPrice(data);
                this.setData({offer: this.data.offer});
            }
        })
    },
    toggleCoupons: function() { // 切换优惠
        this.setData({show: !this.data.show})
    },
    couponCollection: function(e) { // 领取优惠卷
        var index = e.currentTarget.dataset.index;
        var data = 'CouponID=' + this.data.productionInfo.Coupons[index].ID
        wx.request({
            url: app.globalData.serverPath + '/UserCoupon',
            method: "POST",
            header: app.globalData.header,
            data: data,
            success: ({data}) => {
                this.data.productionInfo.Coupons[index].IsReceived = 1;
                this.setData({ productionInfo: this.data.productionInfo})
            },
            fail: err => {
                wx.showToast({
                    title: '领取失败,请稍后再试!',
                    icon: 'none',
                    duration: 1000
                })
            }
        })
        
    },
    addCart: function() { // 加入购物车
        app.checkedUserInfo().then(ok => {
            if (!ok)  return;
            var cart = wx.getStorageSync('cart');
            try {
                cart = JSON.parse(cart);
            } catch (err) {
                cart = []
            }

            if (cart.length) {
                cart.unshift(this.data.printprice)
            } else {
                cart.push(this.data.printprice)
            }
            // console.log(cart);
            var data = JSON.stringify(cart)
            wx.setStorageSync('cart', data)
            app.setCartbadge();
            wx.showModal({
                title: '加入购物车成功',
                content: '是否去结算?',
                success: (res) => {
                    if (res.confirm) {
                        wx.reLaunch({
                            url: '../cart/cart',
                        })
                    }
                }
            })

        })
       
        
        
    },
    buyNow: function() { // 立即购买
        app.checkedUserInfo().then(ok => {

            if (!ok) return;
            var cart = wx.getStorageSync('cart');
            try {
                cart = JSON.parse(cart);
            } catch (err) {
                cart = []
            }

            if (cart.length) {
                cart.unshift(this.data.printprice)
            } else {
                cart.push(this.data.printprice)
            }
            // console.log(cart);
            var data = JSON.stringify(cart)
            wx.setStorageSync('cart', data)
            wx.navigateTo({
                url: '../submit_order/submit_order?model=buynow',
            })
            app.setCartbadge();
        })
    },
    getNowDocument() { // 获取模板数据并复制

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})